package core

import (
	"fmt"
	"net"
	"time"
)

func Iamhere() {

	/*
		ifaces, err := net.Interfaces()
		if err != nil {
			fmt.Print(fmt.Errorf("localAddresses: %+v\n", err.Error()))
			return
		}
		for _, i := range ifaces {
			addrs, err := i.Addrs()
			if err != nil {
				fmt.Print(fmt.Errorf("localAddresses: %+v\n", err.Error()))
				continue
			}
			for _, a := range addrs {
				switch v := a.(type) {
				case *net.IPAddr:
					fmt.Printf("%v : %s (%s)\n", i.Name, v, v.IP.DefaultMask())
				}

			}
		}*/

	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return
	}
	var lip net.IP = nil
	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			ipnet.Network()
			if ipnet.IP.To4() != nil {
				lip = ipnet.IP.To4()
			}
		}
	}
	ticker := time.NewTicker(time.Second * 30)
	go func() {
		for _ = range ticker.C {
			// 这里设置发送者的IP地址，自己查看一下自己的IP自行设定
			if lip != nil {
				laddr := net.UDPAddr{
					IP:   lip, // net.IPv4(192, 168, 137, 224),
					Port: 3000,
				}
				// 这里设置接收者的IP地址为广播地址
				raddr := net.UDPAddr{
					IP:   net.IPv4(255, 255, 255, 255),
					Port: 3000,
				}
				conn, err := net.DialUDP("udp", &laddr, &raddr)
				if err != nil {
					println(err.Error())
					return
				}
				conn.Write([]byte(fmt.Sprintf("%s,%s,%s\r\n", "box.GetName()", "GLOBALUUID", lip)))
				conn.Close()
			}
		}
	}()

}
